package com.fragment;

import static android.content.ContentValues.TAG;
import static android.content.Context.MEDIA_PROJECTION_SERVICE;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.demo.MainActivity;
import com.baidu.location.demo.NotificationUtils;
import com.baidu.location.demo.R;
import com.baidu.location.demo.ScreenActivity;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.AreaUtil;
import com.bumptech.glide.Glide;
import com.business.UpdateApp;
import com.entity.Friends;
import com.entity.Gps;
import com.entity.HubMeesageVM;
import com.entity.User;
import com.microsoft.signalr.HubConnectionState;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogRootLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.service.HubService;
import com.util.DialogUtil;
import com.util.util;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link GpsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class GpsFragment extends Fragment {
    public static String ScreenId;
    public static MediaProjectionManager mediaProjectionManager;
    public static LocationClient mClient;
    public static MapView mMapView;
    private static BaiduMap mBaiduMap;
    private Notification mNotification;
    private boolean isFirstLoc = true;
    private static FragmentActivity activity;
    private ImageView location;
    private MyLocationListener myLocationListener;
    public static Dictionary<String, Marker> coordinate=new Hashtable<>();
    private Dictionary<String,Overlay> overlay=new Hashtable<>();
    private double longitude;
    private double latitude;
    public static LatLng shouPosition=null;
    private List<String> locationClick=new ArrayList<>();
    private Marker oneself;
    public GpsFragment() {

    }

    /**
     * 初始化定位参数
     */
    private void initLocation() {
        // 创建定位客户端
        mClient = new LocationClient(getActivity());
        myLocationListener = new MyLocationListener();
        // 注册定位监听
        mClient.registerLocationListener(myLocationListener);
        LocationClientOption mOption = new LocationClientOption();
        // 可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        mOption.setScanSpan(1000);
        mOption.setCoorType("bd09ll");
        mOption.setOpenGps(true);
        mClient.setLocOption(mOption);
    }

    /**
     * 初始化前台服务
     */
    @SuppressLint("UnspecifiedImmutableFlag")
    private void initNotification () {
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationUtils notificationUtils = new NotificationUtils(getActivity());
            Notification.Builder builder = notificationUtils.getAndroidChannelNotification
                    ("后台持续定位中", "正在后台定位");
            mNotification = builder.build();
        } else {
            Notification.Builder builder = new Notification.Builder(getActivity());
            Intent nfIntent = new Intent(getActivity(), MainActivity.class);

            builder.setContentIntent(PendingIntent.
                    getActivity(getActivity(), 0, nfIntent, 0)) // 设置PendingIntent
                    .setContentTitle("后台持续定位中") // 设置下拉列表里的标题
                    .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                    .setContentText("正在后台定位") // 设置上下文内容
                    .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

            mNotification = builder.build(); // 获取构建好的Notification
        }
        mNotification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
    }
    /**
     * 定位信息回调
     */
    class  MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || mMapView == null) {
                return;
            }
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    if(bdLocation.getLatitude()==4.9E-324&&bdLocation.getLongitude()==4.9E-324)return;
                    if(latitude!=bdLocation.getLatitude()||longitude!=bdLocation.getLongitude()){
                        Bitmap bitmap= util.scaleBitmap(util.getBitmap(MainActivity.user.getHeadPortrait()),150,150,activity);
                        getActivity().runOnUiThread(() -> {
                            LatLng point = new LatLng(bdLocation.getLatitude(),
                                    bdLocation.getLongitude());
                            if(oneself==null){
                                try {
                                    MarkerOptions markerOptions = new MarkerOptions()
                                            .position(point)
                                            .icon(BitmapDescriptorFactory
                                                    .fromBitmap(util.createCircleImage(bitmap)));
                                    oneself= (Marker) mBaiduMap.addOverlay(markerOptions);
                                    oneself.setTitle(MainActivity.user.getId());

                                }catch (Exception e){
                                    Log.d("添加标记",e.getMessage());
                                }
                            }else{
                                oneself.setPosition(point);
                            }

                        });
                    }
                    Log.d(TAG, "latitude"+latitude+";longitude"+longitude);
                    latitude=bdLocation.getLatitude();
                    longitude=bdLocation.getLongitude();
                    Gps gps=new Gps(MainActivity.user.getId(),"", bdLocation.getLatitude(), bdLocation.getLongitude(),"","");
                    gps.setId(MainActivity.user.getId());
                    if(HubService.hubConnection!=null&&HubService.hubConnection.getConnectionState()==HubConnectionState.CONNECTED){
                        for (Friends f:MainActivity.friends) {
                            gps.setReceive(f.getFriendId());
                            HubService.hubConnection.send("Gps",JSONObject.toJSONString(gps));
                        }
                    }
                }
            }.start();

        }
    }
    public static GpsFragment newInstance() {
        return new GpsFragment();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(mMapView!=null)mMapView.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        if(mMapView!=null)mMapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mClient.disableLocInForeground(true);
        mClient.stop();
        mMapView.onDestroy();
        mMapView = null;
        // 关闭前台定位服务
        mClient.disableLocInForeground(true);
        mClient.unRegisterLocationListener(myLocationListener);
        // 停止定位sdk
        mClient.stop();
        shouPosition=null;
        overlay=null;
        coordinate=null;
        mMapView=null;
        mClient=null;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity=getActivity();
        UpdateApp.IsExitNewApp(getActivity());
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    for (int i = 0; i < 500; i++) {
                        if(HubService.hubConnection==null||HubService.hubConnection.getConnectionState()== HubConnectionState.DISCONNECTED){
                            Thread.sleep(200);
                        }else {
                            if(MainActivity.login!=null){
                                MainActivity.login.join();
                            }
                            new Thread(){
                                @Override
                                public void run() {
                                    super.run();
                                    on();
                                }
                            }.start();
                            break;
                        }
                    }
                }catch (Exception e){
                    Log.d(TAG, "连接异常："+e.getMessage());
                }
            }
        }.start();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {

        } else {
            if(shouPosition!=null){
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(shouPosition).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                shouPosition=null;
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        new Thread(){
            @Override
            public void run() {
                super.run();
                if(MainActivity.login==null){
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                   if(MainActivity.login!=null) MainActivity.login.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getActivity().runOnUiThread(() -> {
                    mMapView = getActivity().findViewById(R.id.mv_foreground);
                    location=getActivity().findViewById(R.id.location);
                    mMapView.showZoomControls(false);
                    mBaiduMap = mMapView.getMap();
                    mBaiduMap.setMyLocationEnabled(true);
                    initLocation();
                    initNotification();
                    mClient.enableLocInForeground(1, mNotification);
                    mClient.start();
                    mBaiduMap.setOnMarkerClickListener(marker -> {
                        if(marker.getTitle()==MainActivity.user.getId()) {
                            return false;
                        }
                        Overlay o= overlay.get(marker.getTitle());
                        if(o!=null){
                            o.remove();
                            overlay.remove(marker.getTitle());
                            return false;
                        }
                        locationClick.add(marker.getTitle());
                        List<LatLng> points = new ArrayList<>();
                        points.add(new LatLng(marker.getPosition().latitude,marker.getPosition().longitude));
                        points.add(new LatLng(latitude,longitude));
                        List<Integer> colors = new ArrayList<>();
                        colors.add(Color.BLUE);
                        OverlayOptions mOverlayOptions = new PolylineOptions()
                                .width(10)  
                                .color(0xAAFF0000)
                                .points(points)
                                .colorsValues(colors);//设置每段折线的颜色
                        overlay.put(marker.getTitle(),mBaiduMap.addOverlay(mOverlayOptions));
                        double distance= AreaUtil.calculateArea(new LatLng(latitude,longitude),marker.getPosition());
                        DialogUtil.CreateDoalog(getActivity(),"距离好友："+distance+"米",0, QMUITipDialog.Builder.ICON_TYPE_INFO);
                        return false;
                    });
                    location.setOnClickListener(view -> {
                        LatLng ll = new LatLng(latitude,longitude);
                        MapStatus.Builder builder = new MapStatus.Builder();
                        builder.target(ll).zoom(18.0f);
                         mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                    });
                });
            }
        }.start();
    }
    public void on(){
        HubService.hubConnection.on("data", (json)->{
            try {
                Gps data=JSONObject.parseObject( json,Gps.class);
                Log.d("接收数据：", JSONObject.toJSONString(data));
                Marker overlay=coordinate.get(data.getId());
                LatLng point = new LatLng(data.getLatitude(),data.getLongitude());
                if(overlay==null){
                    Bitmap bitmap=util.scaleBitmap(util.getBitmap(data.getHeadPortrait()),150,150,activity);
                    activity.runOnUiThread(() -> {
                        try {
                            MarkerOptions markerOptions = new MarkerOptions()
                                    .position(point)
                                    .icon(BitmapDescriptorFactory
                                            .fromBitmap(util.createCircleImage(bitmap)));
                            if(mBaiduMap!=null) {
                                Marker o = (Marker) mBaiduMap.addOverlay(markerOptions);
                                o.setTitle(data.getId());
                                coordinate.put(data.getId(),o);
                            }
                        }catch (Exception e){
                            Log.d(TAG, "添加界面标记异常："+e.getMessage());
                        }
                    });
                }else{
                    activity.runOnUiThread(() -> {
                        overlay.setPosition(point);
                    });
                }
            }catch (Exception e){
                Log.d(TAG, "接收异常："+e.getMessage());
            }

        },String.class);
        HubService.hubConnection.on("message",(data)->{
            HubMeesageVM message=JSONObject.parseObject(data,HubMeesageVM.class);
            if(message.getStatus()==0){
                Screen(message);
            }
        },String.class);
    }
    @SuppressLint("NewApi")
    public void Screen(HubMeesageVM message){
        Log.d(TAG, "屏幕:"+message.getData());
        if(message.getData().equals("接受屏幕")){
            QMUIDialog.CustomDialogBuilder customDialog=new QMUIDialog.CustomDialogBuilder(getActivity()){
                @Nullable
                @Override
                protected View onCreateContent(QMUIDialog dialog, QMUIDialogView parent, Context context) {

                    return super.onCreateContent(dialog, parent, context);
                }

                @Override
                protected void onAfterCreate(@NonNull QMUIDialog dialog, @NonNull QMUIDialogRootLayout rootLayout, @NonNull Context context) {
                    super.onAfterCreate(dialog, rootLayout, context);
                    ImageView messageImage=rootLayout.findViewById(R.id.messageImage);
                    TextView messageName=rootLayout.findViewById(R.id.messageName);
                    messageName.setText(message.getUser().getName());
                    Glide.with(getActivity()).load(message.getUser().getHeadPortrait()).into(messageImage);
                }
            }.setLayout(R.layout.messagelistlayout);
            customDialog.addAction("取消", (dialog, index) -> {
                HubMeesageVM hub=new HubMeesageVM();
                hub.setData("拒绝");
                hub.setStatus(0);
                hub.setReceive(message.getUser().getId());
                HubService.hubConnection.send("SendMessage",JSONObject.toJSONString(hub));
                dialog.dismiss();
            });
            customDialog.addAction("同意", (dialog, index) -> {
                dialog.dismiss();
                HubMeesageVM hub=new HubMeesageVM();
                hub.setData("同意");
                hub.setStatus(0);
                hub.setReceive(message.getUser().getId());
                HubService.hubConnection.send("SendMessage",JSONObject.toJSONString(hub));
                getActivity().startActivity(new Intent(getActivity(), ScreenActivity.class));

            });
            getActivity().runOnUiThread(customDialog::show);
        }else if(message.getData().equals("拒绝")){
            DialogUtil.CreateDoalog(getActivity(),"好友拒绝了您的屏幕共享",0,QMUITipDialog.Builder.ICON_TYPE_NOTHING);
        }else if(message.getData().equals("同意")){
            DialogUtil.CreateDoalog(getActivity(),"好友同意了您的屏幕共享！正在加载程序中",0,QMUITipDialog.Builder.ICON_TYPE_NOTHING);
            mediaProjectionManager=(MediaProjectionManager)getActivity().getSystemService(MEDIA_PROJECTION_SERVICE);
            if(mediaProjectionManager!=null){
                ScreenId=message.getUser().getId();
                getActivity().startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(),222);
            }
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_gps, container, false);
    }
}